import 'package:flutter_test1/db/table/account_table.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DbManager {
  static final DbManager _instance = DbManager._internal();

  factory DbManager() => _instance;

  DbManager._internal();

  Database? _database;

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDatabase();
    return _database!;
  }

  Future<Database> _initDatabase() async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, 'app_database.db');

    return openDatabase(
      path,
      version: 1,
      onCreate: _onCreate,
      onUpgrade: _onUpgrade,
    );
  }

  Future<void> _onCreate(Database db, int version) async {
    // 在这里初始化表
    await Future.wait([
      AccountTable().createTable(db)
    ]);
  }

  Future<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
    // 如果有表结构更新，可在此处处理
  }
}
